package com.finalab.yueqiu.interceptor;


import com.finalab.yueqiu.constant.ResponseCode;
import com.finalab.yueqiu.dao.user.UserDAO;
import com.finalab.yueqiu.entity.user.User;
import com.finalab.yueqiu.service.token.TokenServiceImpl;
import com.finalab.yueqiu.util.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class TokenAuthInteceptor implements HandlerInterceptor {

    @Autowired
    TokenServiceImpl tokenServiceImpl;
    @Autowired
    UserDAO userDAO;

    public static final String[] REQUIRE_NOT_AUTH_URLS = new String[]{
            "/user/login", "/user/register", "/phone/auth", "/phone/succeed"
    };

    public boolean containUrls(String url){
        for (String getUrl : REQUIRE_NOT_AUTH_URLS ) {
            if(getUrl.equals(url)){
                return true;
            }
        }
        return false;
    }
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String url = httpServletRequest.getRequestURI();
        if(containUrls(url)){
            return true;
        }
        Cookie[] cookies = httpServletRequest.getCookies();
        String tokenName;
        User user = new User();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    if((tokenName = tokenServiceImpl.getToken(cookie.getValue())) != null){
                        tokenName = tokenName.substring(8);
                        BeanUtils.copyProperties(userDAO.selectById(Integer.valueOf(tokenName)), user);
                        HttpSession session = httpServletRequest.getSession();
                        if(session.getAttribute("id") == null){
                            session.setAttribute("id", tokenName);
                        }
                        return true;
                    }
                }
            }
        }
        ResponseUtil.responseCode(httpServletResponse, ResponseCode.NOT_LOGIN.getValue());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        return;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        return;
    }
}
